<template>
<Modal v-model="modalValue" :title="title">
    <div style="padding-right: 40px;">
        <Form
            ref="addForm"
            :model="form"
            :rules="diyData.rules"
            :label-width="100"
        >
           <FormItem label="角色名称" prop="roleName">
                <Input clearable
                    v-model="form.roleName"
                    placeholder="请输入角色名称"
                ></Input>
            </FormItem>

            <FormItem label="菜单列表" prop="menus">
                <Tree :data="apiData.apiAccessList" @on-check-change="checkChange" ref="tree" show-checkbox ></Tree>
            </FormItem>

        </Form>
        </div>
        <div slot="footer">
            <Button
                type="primary"
                style="width: 90px; margin-right: 20px"
                @click="submit">
                保存
            </Button>
            <Button style="width: 90px" @click="modalCancel()">
                取消
            </Button>
      </div>
</Modal>
</template>

<script>
// import {apiRoleDetail, apiRoleUpdate, apiRoleAdd, apiMenuList} from '@/api/admin';
import {
  roleSelect, roleSave, roleUpdate, roleInfo
} from '@/api/system/role-permissions.js'
import {
  menuList, menuNav
} from '@/api/system/menu.js'
export default {
  name: 'add-role',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    roleId: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      title: '',
      // 表单数据
      form: {
        roleName: '',
        menuIdList: []
      },
      diyData: {
        rules: {
          roleName: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
        },
        menuArr: [] // 反查询菜单
      },
      apiData: {
        apiAccessList: []
      }
    }
  },
  methods: {
    // 获取角色详情
    getDetail () {
      roleInfo({ roleId: this.roleId }).then(res => {
        const { roleName, menuIdList } = res.data.role
        this.form.roleName = roleName
        this.form.menuIdList = menuIdList
        this.selectAuth(menuIdList, this.apiData.apiAccessList)
      })
      this.$forceUpdate()
    },
    // 迭代选择的菜单
    selectAuth (menus, arr) {
      var that=this
      arr=arr.map(res=>{
        var index=menus.findIndex(val=>res.menuId==val)
         
        if(index!=-1){
           this.$set(res, 'checked', true)           
        }
        if (res.children && res.children.length > 0) {
            // 如果存在子菜单，把父菜单选择为空，不然会全部选择上，在提交的时候，用数组去重
            this.$set(res, 'checked', false)
            that.selectAuth(menus, res.children)
        }
        return res
      })

    },
    checkChange (e) {
       console.log(e)
      this.form.menuIdList =e.map(res=>{
        
        return res.menuId
      })
      console.log(this.form.menuIdList)
    },

    // 获取菜单
    getTreeList () {
      menuList().then(res => {
        this.apiData.apiAccessList = []
        this.dealAccessData(res.data)
      })
    },
    // 处理数据
    dealAccessData (data) {
      let map = {}
      data.forEach(item => {
        item.title = item.name
        item.expand=true
        map[item.menuId] = item
      })
      data.forEach(item => {
        let parent = map[item.parentId] // 判断item的pid是否是否存在map中
        if (parent) { // 如果存在则表示item不是最顶层的数据
          (parent.children || (parent.children = [])).push(item)
        } else {
          this.apiData.apiAccessList.push(item) // 如果不存在 则是顶层数据
        }
      })
      // 请求详情
      this.roleId && this.getDetail()
    },
    // 迭代菜单,寻找父级菜单
    getMenuParentIid (form, menu) {
      this.diyData.menuArr = [...new Set(this.diyData.menuArr)]
      form.forEach(item => {
        menu.forEach(citem => {
          if (item == citem.menuId && citem.parentId != 0) {
            this.diyData.menuArr.push(citem.parentId)
          } else if (citem.children && citem.children.length > 0) {
            this.getMenuParentIid(form, citem.children)
          }
        })
      })
    },

    submit () {
      // this.$store.commit('setSpinShow', true)  
      // this.form.menuIdList = []
      // this.$refs.tree.getCheckedAndIndeterminateNodes().forEach(item => {
      //   console.log('item',item.menuId)
      //   if (item.parentId && item.parentId != 0) {
      //     this.form.menuIdList.push(item.menuId)
      //   }
      //   this.form.menuIdList.push(item.menuId)
      // })
      // // 数组去重
      // this.getMenuParentIid(this.form.menuIdList, this.apiData.apiAccessList)
      // // 数组去重
      // this.form.menuIdList = [...new Set([...this.form.menuIdList, ...this.diyData.menuArr])].sort()
      // this.form.menuIdList.splice(this.form.menuIdList.findIndex(item => item == undefined), 1)
      this.form.menuIdList =this.$refs.tree.getCheckedAndIndeterminateNodes().map(item => {
        return item.menuId
      })
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          const opt = { ...this.form }
          if (this.roleId) {
            opt.roleId = this.roleId
            roleUpdate(opt).then(
              (res) => {
                this.$Message.success('编辑成功')
                this.$emit('on-success')
                this.modalCancel()
              }
            ).finally(() => this.$store.commit('setSpinShow', false))
          } else {
            roleSave(opt).then(
              (res) => {
                this.$Message.success('新增成功')
                this.$emit('on-success')
                this.modalCancel()
              }
            ).finally(() => this.$store.commit('setSpinShow', false))
          }
        }
      })
    },
    modalCancel () {
      this.$refs['addForm'].resetFields()
      this.$store.commit('setSpinShow', false)
      this.$nextTick(() => {
        this.modalValue = false
      })
    }
  },
  computed: {
    modalValue: {
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
      }
    }
  },
  watch: {
    value (val) {
      this.$refs['addForm'].resetFields()
      if(val){
        this.getTreeList()
        if (this.roleId) {
          this.title = '编辑角色'
        } else {
          this.title = '新增角色'
        }
      }
      
    }
  },
  mounted () {

  }
}
</script>

<style scoped lang="less">

    .ivu-tree {
        margin: 0;
    }

    .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.6);
        text-align: center;
    }

    .look-img:hover .demo-upload-list-cover {
        display: block;
    }

    .demo-upload-list-cover i {
        line-height: 98px;
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }

    .demo-spin-icon-load {
        animation: ani-demo-spin 1s linear infinite;
    }

</style>
